// packageG/cps/cpsPage/cpsPage.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    components: [],
    page_id: "",
    page_info: {},
    btnFlag: false,

    current_page: 1,
    total_page: 0,
    decorate_isLoadMore: true,
    bottomShowBol: false,
    bottomShowBolIndex: 0,

    showPage: false,
    isWatch: true,//页面浏览权限
    fullShow: false,//首屏广告是否开启
    full_screen: {},
    advertising: {},
    popShow: false,
    
    footshow: false,//底部导航
    foot_type: '',
    bottom_info: {},//底部导航数据
    top_info: {},//顶部导航数据
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.page_id) {
      this.setData({
        page_id: options.page_id,
      });
    }
    if (options.mid) {
      app._setMid(options.mid);
    }
    this.getCPSdata();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getCPSdata();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      bottomShowBol: true,
    });

    if (this.data.decorate_isLoadMore) {
      this.getMoreDecorate();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var value = wx.getStorageSync('yz_uid');
    let mid = '';
    if (value) {
      mid = value;
    }
    return {
      title: this.pageShare?.page_title||'',
      path: `/packageG/cps/cpsPage/cpsPage?page_id=${this.data.page_id}&mid=${mid}`,
    };
  },
  // 获取滚动条当前位置
  onPageScroll: function (e) {
    // 节流
    if (e.scrollTop > 80) {
      if (!this.data.btnFlag) {
        this.setData({
          btnFlag: true,
        });
      }
    } else {
      if (this.data.btnFlag) {
        this.setData({
          btnFlag: false,
        });
      }
    }

    if (this.data.bottomShowBol) {
      this.setData({
        bottomShowBol: false,
      });
    }
  },

  getCPSdata() {
    this.setData({
      showPage: false,
    });
    wx.showLoading({
      title: '加载中'
    });
    let jsons = {
      page_id: this.data.page_id,
    };

    let urlStr = app.getNetAddresss("home-page.index");
    app._getNetWork({
      url: urlStr,
      data: jsons,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          if (res.data.item) {
            this.setData({
              showPage: true,
            });
            wx.stopPullDownRefresh({
              complete: function (res) {
                console.log('关闭下拉刷新', res, new Date());
              }
            });
            let params = res.data.item.pageinfo ? res.data.item.pageinfo.params : {};
            this.setData({
              components: res.data.item.datas,
              page_name: res.data.item.page_info.page_title,
              decorate_isLoadMore: true,
              footshow: true,
              foot_type: res.data.item.foot_type,
              isWatch: params.allowauth == 0 ? false : true
            });
            if (!this.data.isWatch && res.data.item.page_info.member_level_url && res.data.item.page_info.member_level_url.link &&
              res.data.item.page_info.member_level_url.link.indexOf('packageG/index/index') < 0) {
              wx.redirectTo({
                url: res.data.item.page_info.member_level_url.link,//无权限浏览跳转页面
              });
            }

            if (res.data.item.page) {
              this.setData({
                total_page: res.data.item.page.total_page,
                current_page: res.data.item.page.current_page,
                bottomShowBolIndex: res.data.item.page.count - 1,
              });
            }

            wx.setNavigationBarTitle({ title: this.data.page_name });
            if (res.data.item.page_info) {
              this.setData({
                advertising: res.data.item.page_info.advertising_id || {},
                full_screen: res.data.item.page_info.full_screen_id || {},
              });
  
              if (this.data.advertising.id && this.data.advertising.datas) {
                this.data.advertising.datas = JSON.parse(this.data.advertising.datas);
                this.setData({
                  advertising: this.data.advertising,
                });
              }
            }
            this.setPageADData();//设置首屏广告
            this.setFootData(res.data.item);//设置底部导航
            this.pageShare = {
              page_title: res.data.item.page_info.page_title
            }
            if (res.data.item.page_info && res.data.item.page_info.preview_color) {
              wx.setNavigationBarColor({
                backgroundColor: res.data.item.page_info.preview_color,
                frontColor: res.data.item.page_info.font_color == 1 ? '#ffffff' : '#000000',
                animation: {
                  duration: 400,
                  timingFunc: 'easeIn'
                }
              });
            }
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
        }
        wx.hideLoading();
      },
    });
  },
  setFootData(designerItem){
    let top_info = {};
    let bottom_info = {};
    if (designerItem.top && designerItem.top.id) {
      top_info = JSON.parse(designerItem.top.page_info)//顶部导航数据
    }
    // 装修的底部有三种情况
    if (designerItem.foot_type == 1) {
      // 显示默认
      if (!designerItem.foot || !designerItem.foot.page_info) {
        // 显示系统默认
      } else {
        // 显示列表设置的默认
        bottom_info = JSON.parse(designerItem.foot.page_info)
      }
    } else if (designerItem.foot_type == 2) {
      // 显示自定义的底部导航
      if (designerItem.foot instanceof Array) {
        bottom_info = {}
      } else {
        bottom_info = JSON.parse(designerItem.foot.page_info)
      }
    }
    this.setData({
      top_info,bottom_info
    });
  },
  setPageADData(){
    let fullAdvertisement = wx.getStorageSync('fullAdvertisement');
    if (this.data.full_screen && this.data.full_screen.id && !fullAdvertisement && this.data.full_screen.show_rule === 1) {
      wx.setStorageSync('fullAdvertisement', true);
      this.setData({
        fullShow: true
      });
      setTimeout(() => {
        this.countDown(this.data.full_screen.show_time);
      }, 2000);
    }

    let fullAdvertisement_expiration = wx.getStorageSync('fullAdvertisement_expiration');
    let newTime = parseInt(Date.parse(new Date()) / 1000);

    if (this.data.full_screen && this.data.full_screen.id && this.data.full_screen.show_rule === 2 && fullAdvertisement_expiration < newTime) {
      let timestamp = parseInt((new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1) / 1000); //当天23:59:59
      wx.setStorageSync("fullAdvertisement_expiration", timestamp);
      this.setData({
        fullShow: true
      });
      setTimeout(() => {
        this.countDown(this.data.full_screen.show_time);
      }, 2000);
    }

    // 新弹窗广告
    let popAdvertisement = wx.getStorageSync('popAdvertisement');
    if (this.data.advertising && this.data.advertising.id && !popAdvertisement && this.data.advertising.show_rule === 1) {
      wx.setStorageSync('popAdvertisement', true);
      this.setData({
        popShow: true
      });
    }

    let popAdvertisement_expiration = wx.getStorageSync('popAdvertisement_expiration');
    let pop_newTime = parseInt(Date.parse(new Date()) / 1000);
    if (this.data.advertising && this.data.advertising.id && this.data.advertising.show_rule === 2 && popAdvertisement_expiration < pop_newTime) {
      let timestamp = parseInt((new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1) / 1000); //当天23:59:59
      wx.setStorageSync("popAdvertisement_expiration", timestamp);
      //每日小程序登录弹出
      this.setData({
        popShow: true
      });
    }
  },
  turnFullTo() {
    let url = this.data.full_screen.minapp_link;
    try {
      wx.navigateTo({
        url: url
      });
    } catch (e) {
      wx.showToast({
        title: '链接设置错误',
        icon: 'none',
        duration: 2000
      });
    }
  },
  closeFull() {
    this.setData({
      fullShow: false
    });
  },
  turnTo() {
    if (this.data.advertising.is_minapp == 2) {
      if (this.data.advertising.minapp_sid) {
        if (this.data.advertising.minapp_link2) {
          try {
            wx.navigateToMiniProgram({
              appId: this.data.advertising.minapp_sid,
              path: this.data.advertising.minapp_link2,
              extraData: {},
              envVersion: 'release',
              success(res) {
                // 打开成功
              },
              fail(res) {
                wx.showToast({
                  title: '小程序跳转失败',
                  icon: 'none',
                  duration: 2000
                });
              }
            });
          } catch (e) {
            wx.showToast({
              title: '小程序跳转失败',
              icon: 'none',
              duration: 2000
            });
          }
        } else {
          wx.showToast({
            title: '请设置跳转小程序后的跳转链接',
            icon: 'none',
            duration: 2000
          });
        }
      } else {
        wx.showToast({
          title: '请设置小程序所需跳转appId',
          icon: 'none',
          duration: 2000
        });
      }
    } else {
      let url = this.data.advertising.minapp_link;
      try {
        wx.navigateTo({
          url: url
        });
      } catch (e) {
        wx.showToast({
          title: '链接设置错误',
          icon: 'none',
          duration: 2000
        });
      }
    }
  },
  closePop() {
    this.setData({
      popShow: false
    });
  },
  countDown(num) {
    let numberNum = num;
    this.setData({
      'full_screen.show_time': numberNum,
      'advertisement.time': numberNum
    });
    numberNum--;

    let cleartime = setTimeout(() => {
      if (numberNum <= 0) {
        this.setData({
          fullShow: false
        });
        clearInterval(cleartime);
      } else {
        this.countDown(numberNum);
      }
    }, 1000);
  },

  getMoreDecorate() {
    this.setData({
      decorate_isLoadMore: false,
    });

    if (this.data.current_page < this.data.total_page) {
      this.setData({
        current_page: this.data.current_page + 1,
      });
      let urlStr = app.getNetAddresss(
        "plugin.decorate.frotend.decorate-api.get-page"
      );
      app._postNetWork({
        url: urlStr,
        data: {
          decorate_page: this.data.current_page,
          decorate_id: this.data.page_id,
        },
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            this.setData({
              decorate_isLoadMore: true,
              components: this.data.components.concat(res.data.datas),
            });
          } else {
            this.setData({
              decorate_isLoadMore: false,
              current_page: this.data.current_page - 1,
            });
          }
        },
      });
    }
  },
});